package org.jeecg.modules.achachievementstandard.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achachievementstandard.entity.AchAchievementStandard;
import org.jeecg.modules.achachievementstandard.service.IAchAchievementStandardService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achachievementstandard.vo.AchAchievementStandardVo;
import org.jeecg.modules.achachievestandarditem.entity.AchAchieveStandardItem;
import org.jeecg.modules.achachievestandarditem.service.IAchAchieveStandardItemService;
import org.jeecg.modules.common.api.ISysInfo;
import org.jeecg.modules.relation.relachstandarddistribution.entity.RelAchStandardDistribution;
import org.jeecg.modules.relation.relachstandarddistribution.service.IRelAchStandardDistributionService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: ach_achievement_standard
 * @author: baochangrong
 * @Date:   2022-03-16
 * @Version: V1.0
 */
@Api(tags="ach_achievement_standard")
@RestController
@RequestMapping("/achachievementstandard/achAchievementStandard")
@Slf4j
public class AchAchievementStandardController extends JeecgController<AchAchievementStandard, IAchAchievementStandardService> {
	@Autowired
	private IAchAchievementStandardService achAchievementStandardService;
	@Autowired
	private IAchAchieveStandardItemService achAchieveStandardItemService;
	@Autowired
	private IRelAchStandardDistributionService relAchStandardDistributionService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private ISysInfo sysInfo;
	
	/**
	 * 分页列表查询
	 *
	 * @param achAchievementStandard
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-分页列表查询")
	@ApiOperation(value="ach_achievement_standard-分页列表查询", notes="ach_achievement_standard-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AchAchievementStandard achAchievementStandard,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AchAchievementStandard> queryWrapper = QueryGenerator.initQueryWrapper(achAchievementStandard, req.getParameterMap());
		Page<AchAchievementStandard> page = new Page<AchAchievementStandard>(pageNo, pageSize);
		IPage<AchAchievementStandard> pageList = achAchievementStandardService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/** vo全部查询 附带关联字段名称 */
	@AutoLog(value = "getVoAll-分页列表查询")
	@ApiOperation(value="getVoAll-分页列表查询", notes="getVoAll-分页列表查询")
	@GetMapping(value = "/getVoAll")
	public Result<?> queryPageList(@Param("achAchievementStandardVo") AchAchievementStandardVo achAchievementStandardVo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		//获取当前登录用户信息
		String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String username = JwtUtil.getUsername(token);
		LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户

		String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
		String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）
		String departId = sysBaseAPI.getDepartIdsByOrgCode(sysOrgCode);//获取当前用户设置的部门id
		List<String> subDepIdsList = sysBaseAPI.getSubDepIdsByDepId(departId); //获取下级部门的部门id，自定义改造sysBaseAPI
		String subDepSysOrgCode = sysBaseAPI.getSubDepOrgCodesByDepId(departId); //直接获取下级部门的orgcode，自定义改造sysBaseAPI

		int userIdentity = loginUser.getUserIdentity();//获取当前登录用户身份

		achAchievementStandardVo.setTenantId(tenantId);
		achAchievementStandardVo.setSysOrgCode(subDepSysOrgCode);//存在多值情况
		Page<AchAchievementStandardVo> page = new Page<AchAchievementStandardVo>(pageNo, pageSize);
		IPage<AchAchievementStandardVo> pageList = achAchievementStandardService.getVoAll(page, achAchievementStandardVo);
		return Result.OK(pageList);
	}

	
	/**
	 *   添加
	 *
	 * @param achAchievementStandard
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-添加")
	@ApiOperation(value="ach_achievement_standard-添加", notes="ach_achievement_standard-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AchAchievementStandard achAchievementStandard,HttpServletRequest req) {
		String tenantId = req.getHeader("tenant-id");
		achAchievementStandard.setTenantId(tenantId);
		achAchievementStandardService.save(achAchievementStandard);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param achAchievementStandard
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-编辑")
	@ApiOperation(value="ach_achievement_standard-编辑", notes="ach_achievement_standard-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AchAchievementStandard achAchievementStandard) {
		achAchievementStandardService.updateById(achAchievementStandard);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-通过id删除")
	@ApiOperation(value="ach_achievement_standard-通过id删除", notes="ach_achievement_standard-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		achAchievementStandardService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-批量删除")
	@ApiOperation(value="ach_achievement_standard-批量删除", notes="ach_achievement_standard-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.achAchievementStandardService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "ach_achievement_standard-通过id查询")
	@ApiOperation(value="ach_achievement_standard-通过id查询", notes="ach_achievement_standard-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AchAchievementStandard achAchievementStandard = achAchievementStandardService.getById(id);
		if(achAchievementStandard==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(achAchievementStandard);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param achAchievementStandard
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchAchievementStandard achAchievementStandard) {
        return super.exportXls(request, achAchievementStandard, AchAchievementStandard.class, "ach_achievement_standard");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchAchievementStandard.class);
    }

	 /**
	  * 动态新增 - 上级标准及分项标准数据
	  * dynamicAdd
	  */
	 @AutoLog(value = "ach_achievement_standard-动态新增")
	 @ApiOperation(value="ach_achievement_standard-动态新增", notes="ach_achievement_standard-动态新增")
	 @PostMapping(value = "/dynamicAdd")
	 public Result<?> dynamicAdd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
		 String paperId = jsonObject.getString("paperId");
	 	 //先新增上级标准数据
		 //将JSONObject直接转成AchAchievementStandard实体，（注意字段名要与实体一致）
		 AchAchievementStandard achAchievementStandard = JSONObject.toJavaObject(jsonObject.getJSONObject("achAchievementStandard"),AchAchievementStandard.class);
		 sysInfo.querySysInfoCloneObj(req,achAchievementStandard);//此共用方法可将创建时间、修改时间、创建人、租户、部门等可赋值
		 achAchievementStandard.setUpdateTime(null);
		 achAchievementStandard.setUpdateBy(null);
		 if (!achAchievementStandardService.save(achAchievementStandard)){
			 return Result.error("新增标准失败！");
		 }
		 //先新增分项标准数据
		 JSONArray standardItemMapList = jsonObject.getJSONArray("achAchieveStandardItem");
		 for (int i = 0; i < standardItemMapList.size(); i++) {
		 	 //将JSONObject直接转成AchAchieveStandardItem实体，（注意字段名要与实体一致）
			 AchAchieveStandardItem achAchieveStandardItem =  JSONObject.toJavaObject(standardItemMapList.getJSONObject(i),AchAchieveStandardItem.class);
			 sysInfo.querySysInfoCloneObj(req,achAchieveStandardItem);//此共用方法可将创建时间、修改时间、创建人、租户、部门等可赋值
			 achAchieveStandardItem.setAchievementStandardId(achAchievementStandard.getId());//新增的上级标准id
			 achAchieveStandardItem.setUpdateTime(null);
			 achAchieveStandardItem.setUpdateBy(null);
			 if (!achAchieveStandardItemService.save(achAchieveStandardItem)){
				 return Result.error("新增分项标准失败！");
			 }
		 }
		 //建立试卷与标准关系数据，对RelAchStandardDistribution实体进行操作（rel_ach_standard_distribution表）
		 RelAchStandardDistribution relAchStandardDistribution = new RelAchStandardDistribution();
		 sysInfo.querySysInfoCloneObj(req,relAchStandardDistribution);//此共用方法可将创建时间、修改时间、创建人、租户、部门等可赋值
		 relAchStandardDistribution.setAchievementStandardId(achAchievementStandard.getId());//新增的上级标准id
		 relAchStandardDistribution.setRelObjId(paperId);//paperId试卷id
		 relAchStandardDistribution.setRelObjType("1");
		 relAchStandardDistribution.setPaperStandardEffective(1);//是否有效(1有效，0无效）
		 if (!relAchStandardDistributionService.save(relAchStandardDistribution)){
			 return Result.error("试卷标准关系建立失败！");
		 }
		 return Result.OK("新增成功！");
	 }


	 /**
	  * 动态只新增标准明细 - 对已有上级标准数据情况
	  * dynamicItemAdd
	  */
	 @AutoLog(value = "ach_achievement_standard-动态只新增标准明细")
	 @ApiOperation(value="ach_achievement_standard-动态只新增标准明细", notes="ach_achievement_standard-动态只新增标准明细")
	 @PostMapping(value = "/dynamicItemAdd")
	 public Result<?> dynamicItemAdd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
		 //先新增分项标准数据
		 JSONArray standardItemMapList = jsonObject.getJSONArray("achAchieveStandardItem");
		 for (int i = 0; i < standardItemMapList.size(); i++) {
			 //将JSONObject直接转成AchAchieveStandardItem实体，（注意字段名要与实体一致）
			 AchAchieveStandardItem achAchieveStandardItem =  JSONObject.toJavaObject(standardItemMapList.getJSONObject(i),AchAchieveStandardItem.class);
			 sysInfo.querySysInfoCloneObj(req,achAchieveStandardItem);//此共用方法可将创建时间、修改时间、创建人、租户、部门等可赋值
			 achAchieveStandardItem.setUpdateTime(null);
			 achAchieveStandardItem.setUpdateBy(null);
			 if (!achAchieveStandardItemService.save(achAchieveStandardItem)){
				 return Result.error("新增分项标准失败！");
			 }
		 }
		 return Result.OK("新增成功！");
	 }

 }
